import tkinter as tk
from tkinter import ttk
from graphics.TextBox import TextBox
import random
import time
from graphics.Shape import *


class TextBoxTester:
    def __init__(self, root):
        self.root = root
        self.root.title("文本框测试工具 v1.0")
        self.root.geometry("800x600")

        # 测试用画布
        self.canvas = tk.Canvas(self.root, bg='white')
        self.canvas.pack(fill=tk.BOTH, expand=True)

        # 测试对象池
        self.text_boxes = []
        self.current_textbox = None

        # 控制面板
        self._setup_control_panel()

        # 事件绑定
        self.canvas.bind("<Button-1>", self.select_textbox)
        self.canvas.bind("<B1-Motion>", self.drag_textbox)

    def _setup_control_panel(self):
        """创建右侧控制面板（网页2的布局方案）"""
        control_frame = ttk.LabelFrame(self.root, text="控制")
        control_frame.pack(side=tk.RIGHT, fill=tk.Y, padx=5)

        # 创建文本框按钮
        ttk.Button(control_frame, text="新建文本框",
                   command=self.create_textbox).pack(pady=5)

        # 字体设置
        self.font_size = ttk.Spinbox(control_frame, from_=8, to=36, width=5)
        self.font_size.set(12)
        self.font_size.pack(pady=5)

        # 颜色选择
        ttk.Button(control_frame, text="文字颜色",
                   command=self.choose_color).pack(pady=5)

        # 保存/加载测试
        ttk.Button(control_frame, text="序列化测试",
                   command=self.serialization_test).pack(pady=10)

    def create_textbox(self):
        """创建新文本框（网页5的交互模式）"""
        new_box = TextBox(
            x=400, y=300,
            text="可编辑文本",
            font_size=int(self.font_size.get()),
            color="#FF0000",
            line_width=1
        )
        self.text_boxes.append(new_box)
        self.redraw()

    def select_textbox(self, event):
        """选择并激活文本框（网页4的碰撞检测）"""
        for box in reversed(self.text_boxes):
            if box.contains(event.x, event.y):
                self.current_textbox = box
                self.enter_edit_mode(event)
                break

    def enter_edit_mode(self, event):
        """进入编辑模式（网页1的Entry控件集成）"""
        if self.current_textbox:
            self.current_textbox.start_edit()
            self.current_textbox._draw_editable(self.canvas)  # 显示编辑框
            self.root.update()  # 强制刷新界面

    def drag_textbox(self, event):
        """拖拽移动测试（网页3的坐标更新）"""
        if self.current_textbox and not self.current_textbox.editing:
            dx = event.x - self.current_textbox.x
            dy = event.y - self.current_textbox.y
            self.current_textbox.move(dx, dy)
            self.redraw()

    def choose_color(self):
        """颜色选择功能测试"""
        color = tk.colorchooser.askcolor()[1]
        if color and self.current_textbox:
            self.current_textbox.color = color
            self.redraw()

    def serialization_test(self):
        """序列化往返测试（网页6的字典转换）"""
        if self.current_textbox:
            data = self.current_textbox.to_dict()
            new_box = TextBox.from_dict(data)
            new_box.x += 50  # 偏移显示
            self.text_boxes.append(new_box)
            self.redraw()

    def redraw(self):
        """重绘所有元素（网页7的分层渲染）"""
        self.canvas.delete("all")
        for box in self.text_boxes:
            box.draw(self.canvas)
            if box.selected:
                # 绘制选择框
                x1, y1, x2, y2 = box.get_bounding_box()
                self.canvas.create_rectangle(
                    x1 - 5, y1 - 5, x2 + 5, y2 + 5,
                    outline='blue', dash=(4, 2)
                )

"""$测试程序$"""


class RectangleTestApp(tk.Tk):
    """
    矩形测试类
    """
    def __init__(self):
        import warnings
        warnings.filterwarnings("ignore", category=UserWarning, module="PIL")
        super().__init__()
        self.title("矩形变换测试")
        self.canvas = tk.Canvas(self, width=800, height=600, bg='white')
        self.canvas.pack()

        # 测试用例1：基础矩形（无变换）[1,4](@ref)
        self.rect1 = Rectangle(
            (100, 100), (300, 200),
            color="blue", line_width=2
        )
        self.rect1.draw(self.canvas)

        # 测试用例2：旋转变换矩形[6,8](@ref)
        self.rect2 = Rectangle(
            (400, 300), (600, 400),
            color="green", line_width=3
        )
        self.rect2.rotate(45)  # 45度旋转
        self.rect2.draw(self.canvas)

        # 测试用例3：非等比缩放矩形[7](@ref)
        self.rect3 = Rectangle(
            (500, 100), (700, 250),
            color="red", line_width=4,
            transform=[1.5, 0, 0, 0.8, 0, 0]  # X轴缩放1.5，Y轴缩放0.8
        )
        self.rect3.draw(self.canvas)

        # 测试用例4：平移+剪切变换[6,7](@ref)
        self.rect4 = Rectangle(
            (50, 400), (250, 550),
            color="purple", line_width=1,
            transform=[1, 0.3, 0, 1, 100, 50]  # 剪切变换矩阵
        )
        self.rect4.draw(self.canvas)

        # 添加控制按钮[1,4](@ref)
        btn_frame = tk.Frame(self)
        tk.Button(btn_frame, text="清空画布", command=self.clear_canvas).pack(side=tk.LEFT)
        tk.Button(btn_frame, text="随机变换", command=self.random_transform).pack(side=tk.LEFT)
        btn_frame.pack(side=tk.BOTTOM)

    def clear_canvas(self):
        self.canvas.delete("all")

    def random_transform(self):
        """随机应用仿射变换[6,7](@ref)"""
        for rect in [self.rect1, self.rect2, self.rect3, self.rect4]:
            # 生成随机变换参数
            angle = random.randint(-45, 45)
            scale_x = random.uniform(0.5, 2.0)
            scale_y = random.uniform(0.5, 2.0)
            dx = random.randint(-50, 50)
            dy = random.randint(-50, 50)

            # 应用复合变换
            rect.transform_matrix = [
                scale_x * math.cos(math.radians(angle)),
                -scale_x * math.sin(math.radians(angle)),
                scale_y * math.sin(math.radians(angle)),
                scale_y * math.cos(math.radians(angle)),
                dx,
                dy
            ]
        self.canvas.delete("all")
        for rect in [self.rect1, self.rect2, self.rect3, self.rect4]:
            rect.draw(self.canvas)

class EllipseTestApp(tk.Tk):
    """

    椭圆测试类
    """
    def __init__(self):
        import warnings
        warnings.filterwarnings("ignore", category=UserWarning, module="PIL")
        super().__init__()
        self.title("椭圆变换测试")
        self.canvas = tk.Canvas(self, width=800, height=600, bg='white')
        self.canvas.pack()

        # 测试用例初始化
        self.ellipses = [
            # 基础椭圆（无变换）
            Ellipse(400, 300, 100, 60, color="blue", line_width=2),
            # 旋转变换椭圆
            Ellipse(200, 200, 80, 40, color="green", line_width=3),
            # 非等比缩放椭圆
            Ellipse(600, 100, 120, 80, color="red", line_width=4,
                    transform=[1.5, 0, 0, 0.8, 0, 0]),
            # 平移+剪切变换椭圆
            Ellipse(100, 500, 60, 30, color="purple", line_width=1,
                    transform=[1, 0.3, 0, 1, 50, -20])
        ]

        # 应用初始变换并绘制
        self.ellipses[1].rotate(45)  # 旋转45度
        self.draw_all()

        # 添加控制按钮
        btn_frame = tk.Frame(self)
        tk.Button(btn_frame, text="清空画布", command=self.clear_canvas).pack(side=tk.LEFT)
        tk.Button(btn_frame, text="随机变换", command=self.random_transform).pack(side=tk.LEFT)
        btn_frame.pack(side=tk.BOTTOM)

    def draw_all(self):
        """绘制所有椭圆"""
        self.canvas.delete("all")
        for ellipse in self.ellipses:
            ellipse.draw(self.canvas)

    def clear_canvas(self):
        self.canvas.delete("all")

    def random_transform(self):
        """随机应用仿射变换"""
        for ellipse in self.ellipses:
            # 生成随机变换参数
            angle = random.randint(-45, 45)
            scale_x = random.uniform(0.5, 2.0)
            scale_y = random.uniform(0.5, 2.0)
            dx = random.randint(-50, 50)
            dy = random.randint(-50, 50)

            # 应用复合变换（缩放+旋转+平移）
            ellipse.transform_matrix = [
                scale_x * math.cos(math.radians(angle)),
                -scale_x * math.sin(math.radians(angle)),
                scale_y * math.sin(math.radians(angle)),
                scale_y * math.cos(math.radians(angle)),
                dx,
                dy
            ]
        self.draw_all()





class DrawingApp(tk.Tk):
    """

    圆,直线测试类
    """
    def __init__(self):
        import warnings
        warnings.filterwarnings("ignore", category=UserWarning, module="PIL")
        super().__init__()
        # 创建800*600画布
        self.canvas = tk.Canvas(self, width=800, height=600, bg='white')
        self.canvas.pack()

        # 测试圆形碰撞
        c = Circle(100, 100, 50)
        print(c.contains(120, 120))  # 应返回True

        # 测试矩形碰撞
        r = Rectangle((80, 80), (120, 120))
        print(r.contains(100, 100))  # 应返回True

        """直线类的测试"""
        self.line1 = Line(100, 100, 700, 500,
                          color="green", line_width=2,
                          transform=[1, 0.5, 0, 1, 0, 0])  # 含剪切变换
        self.line1.draw(self.canvas)

        self.line2 = Line(200, 300, 600, 200,
                          color="navy", line_width=4)
        self.line2.rotate(30)  # 应用30度旋转
        self.line2.draw(self.canvas)


        """圆形类的测试"""
        # 基础圆形
        self.circle1 = Circle(400, 300, 50, color="red")

        # 画布中心坐标
        self.circle1.draw(self.canvas)

        # 创建带旋转变换的圆
        self.circle2 = Circle(500, 400, 50,
                              color="red", line_width=4)
        self.circle2.rotate(45) # 应用45度旋转矩阵
        self.circle2.draw(self.canvas)

        # 添加交互按钮
        btn_clear = tk.Button(self, text="清空画布", command=self.clear_canvas)
        btn_clear.pack(side=tk.BOTTOM)

    def clear_canvas(self):
        self.canvas.delete("all")


import tkinter as tk


class CircleFillTest(tk.Tk):
    def __init__(self):
        super().__init__()
        self.canvas = tk.Canvas(self, width=600, height=400)
        self.canvas.pack()

        # 测试用例：变换+填充
        Circle(200, 200, 50,
               color="red",
               fill="#FF9696",  # 使用十六进制格式
               auto_fill=True,
               transform=[1.2, 0, 0, 0.8, 50, 30]).draw(self.canvas)

        # 标准圆形
        Circle(400, 200, 80,
               color="blue",
               fill="#ADD8E6",
               auto_fill=True).draw(self.canvas)


class RectangleFillTest(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("矩形填充测试 (2023年05月10日)")
        self.canvas = tk.Canvas(self, width=800, height=600, bg='white')
        self.canvas.pack()

        # 基础填充测试
        Rectangle((50, 50), (200, 150),
                  color="#FF0000",
                  fill="#FFC0CB",  # 粉红填充
                  auto_fill=True).draw(self.canvas)

        # 渐变填充测试（网页7方法扩展）
        for i in range(5):
            Rectangle((250 + i * 10, 50 + i * 10), (400 + i * 10, 150 + i * 10),
                      color=f"#00{30 * i:02x}FF",  # 蓝色渐变
                      fill=f"#{255 - 30 * i:02x}FF{255 - 30 * i:02x}",  # 蓝绿渐变
                      line_width=2,
                      auto_fill=True).draw(self.canvas)

        # 变换测试（网页6坐标系修正）
        r = Rectangle((500, 100), (700, 200),
                      color="navy",
                      fill=(173, 216, 230),  # RGB元组测试
                      transform=[1.2, 0.3, -0.2, 0.8, 50, 30])
        r.rotate(30)  # 30度旋转
        r.draw(self.canvas)

        # 不同线宽测试（网页5优化方案）
        self._test_line_widths()

        # 控制面板
        btn_frame = tk.Frame(self)
        tk.Button(btn_frame, text="清空", command=self.clear).pack(side=tk.LEFT)
        tk.Button(btn_frame, text="随机", command=self.random).pack(side=tk.LEFT)
        btn_frame.pack()

    def _test_line_widths(self):
        """线宽对比测试"""
        # 中线宽（使用中点算法）
        Rectangle((50, 400), (200, 500),
                  color="green",
                  fill="#90EE90",
                  line_width=2,
                  auto_fill=True).draw(self.canvas)

        # 大线宽（使用Tkinter原生方法）
        Rectangle((250, 400), (400, 500),
                  color="purple",
                  fill="#E6E6FA",
                  line_width=5,
                  auto_fill=True).draw(self.canvas)

    def clear(self):
        self.canvas.delete("all")

    def random(self):
        """随机生成测试矩形（网页7性能测试）"""
        colors = ["#" + "".join(f"{random.randint(0, 255):02x}" for _ in range(3))
                  for _ in range(5)]

        for _ in range(3):
            x1 = random.randint(50, 700)
            y1 = random.randint(50, 500)
            Rectangle((x1, y1),
                      (x1 + random.randint(50, 150), y1 + random.randint(50, 150)),
                      color=random.choice(colors),
                      fill=random.choice(colors),
                      line_width=random.choice([1, 2, 5]),
                      transform=[random.uniform(0.5, 2), 0, 0, random.uniform(0.5, 2), 0, 0]
                      ).draw(self.canvas)


class EllipseFillTest(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("椭圆填充测试 (2025年05月10日)")
        self.canvas = tk.Canvas(self, width=800, height=600, bg='white')
        self.canvas.pack()

        # 基础填充测试[1,7](@ref)
        Ellipse.midpoint_ellipse(self.canvas, 200, 150, 80, 40,
                                 fill="#FFC0CB",  # 粉红填充
                                 color="#FF0000")  # 红色边框

        # 变换测试（旋转变换矩阵）[4](@ref)
        e = Ellipse(500, 200, 60, 30,
                    color="navy",
                    fill=(173, 216, 230),  # RGB元组测试
                    transform=[1.2, 0.3, -0.2, 0.8, 50, 30])
        e.rotate(45)  # 45度旋转
        e.draw(self.canvas)

        # 线宽对比测试[2,7](@ref)
        self._test_line_widths()

        # 边缘条件测试
        Ellipse.midpoint_ellipse(self.canvas, 700, 500, 3, 1,
                                 fill="#FFFFFF",
                                 color="#000000")

        # 控制面板
        btn_frame = tk.Frame(self)
        tk.Button(btn_frame, text="清空", command=self.clear).pack(side=tk.LEFT)
        tk.Button(btn_frame, text="随机", command=self.random).pack(side=tk.LEFT)
        btn_frame.pack()

    def _test_line_widths(self):
        """线宽对比测试"""
        # 中线宽（中点算法）
        Ellipse.midpoint_ellipse(self.canvas, 100, 400, 50, 30,
                                 fill="#90EE90",
                                 color="green",
                                 line_width=2)

        # 大线宽（原生方法）
        e = Ellipse(300, 400, 70, 40,
                    color="purple",
                    fill="#E6E6FA",
                    line_width=5)
        e.draw(self.canvas)

    def clear(self):
        self.canvas.delete("all")

    def random(self):
        """随机生成测试椭圆[2](@ref)"""
        colors = ["#" + "".join(f"{random.randint(0, 255):02x}" for _ in range(3))
                  for _ in range(5)]

        for _ in range(3):
            Ellipse.midpoint_ellipse(self.canvas,
                                     random.randint(100, 700),
                                     random.randint(100, 500),
                                     random.randint(20, 80),
                                     random.randint(10, 40),
                                     fill=random.choice(colors),
                                     color=random.choice(colors),
                                     line_width=random.choice([1, 2, 5]))



"""图形类的测试"""
# if __name__ == "__main__":

    # app = EllipseFillTest()
    # app.mainloop()

    # app = RectangleFillTest()
    # app.mainloop()

    # app = CircleFillTest()
    # app.mainloop()

    # app = DrawingApp()
    # app.mainloop()
    # app = RectangleTestApp()
    # app.mainloop()
    # app = EllipseTestApp()
    # app.mainloop()
"""TextBoxTest"""
# if __name__ == "__main__":
    # root = tk.Tk()
    # app = TextBoxTester(root)
    #
    # # 添加测试用例
    # test_box = TextBox(100, 100, text="测试旋转", font_size=14)
    # test_box.rotate(45)  # 测试旋转变换
    # app.text_boxes.append(test_box)
    #
    # root.mainloop()
